# Python 2/3 兼容性导入

from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import

try:
    from modules.utils.python_compatibility import (
        PY2, PY3, ensure_str, ensure_bytes, format_string,
        dict_items, dict_keys, dict_values, print_function
    )
except ImportError:
    # 如果兼容性模块不可用，使用基本兼容性
    import sys
    PY2 = sys.version_info[0] == 2
    PY3 = sys.version_info[0] == 3
    
    def ensure_str(s, encoding='utf-8'):
        if PY3:
            return str(s) if not isinstance(s, bytes) else s.decode(encoding)
        else:
            return str(s) if not isinstance(s, unicode) else s.encode(encoding)
    
    def ensure_bytes(s, encoding='utf-8'):
        if PY3:
            return s.encode(encoding) if isinstance(s, str) else bytes(s)
        else:
            return str(s) if not isinstance(s, unicode) else s.encode(encoding)
    
    def format_string(template, *args, **kwargs):
        try:
            return template.format(*args, **kwargs)
        except (KeyError, ValueError):
            if args and not kwargs:
                return template % args
            return template
    
    def dict_items(d):
        return list(d.items()) if PY3 else d.items()
    
    def dict_keys(d):
        return list(d.keys()) if PY3 else d.keys()
    
    def dict_values(d):
        return list(d.values()) if PY3 else d.values()
    
    if PY2:
        def print_function(*args, **kwargs):
            sep = kwargs.get('sep', ' ')
            end = kwargs.get('end', '\n')
            file_obj = kwargs.get('file', sys.stdout)
            output = sep.join(str(arg) for arg in args) + end
            file_obj.write(output)
            file_obj.flush()
    else:
        print_function = print

import os
import sys
import json
import time
import psutil
import subprocess
from typing import Dict, List, Tuple, Optional, Any
from dataclasses import dataclass, asdict
from enum import Enum

# 导入模块
try:
    from core.distro_detection import detect_linux_distro
    from modules.persistence.backdoor_checks import check_system_info
    from modules.persistence.ssh_checks import check_ssh_service_status
    from core.utils import color_green, color_yellow, color_red, color_blue
    from core.safe_attribute_accessor import SafeAttributeAccessor, safe_getattr, safe_hasattr
    
except ImportError as e:
    print("导入模块失败: {}".format(e))


class ThreatLevel(Enum):
    """威胁等级枚举"""
    LOW = "low"
    MEDIUM = "medium"
    HIGH = "high"
    CRITICAL = "critical"


class BackdoorType(Enum):
    """后门类型枚举"""
    SSH_KEY = "ssh_key"
    CRONTAB = "crontab"
    BASH_ALIAS = "bash_alias"
    STRACE = "strace"
    SYSTEM_SERVICE = "system_service"
    ENVIRONMENT = "environment"
    SSH_CONFIG = "ssh_config"
    NETWORK = "network"
    USER_ACCOUNT = "user_account"
    # 新增后门类型
    # KERNEL_MODULE = "kernel_module"        # 内核模块后门 - 已禁用，不采用内核级后门
    LIBRARY_HIJACK = "library_hijack"      # 库劫持后门
    CONTAINER_ESCAPE = "container_escape"   # 容器逃逸后门
    DOCKER_SOCKET = "docker_socket"        # Docker套接字后门
    SYSTEMD_TIMER = "systemd_timer"        # Systemd定时器后门
    # PAM_MODULE = "pam_module"              # PAM模块后门 - 已禁用，不采用PAM模块后门
    IPTABLES_RULE = "iptables_rule"        # iptables规则后门
    DNS_HIJACK = "dns_hijack"              # DNS劫持后门
    PROCESS_INJECT = "process_inject"       # 进程注入后门
    MEMORY_RESIDENT = "memory_resident"     # 内存驻留后门


@dataclass
class SystemEnvironment:
    """系统环境信息"""
    distro: str = "unknown"
    version: str = "unknown"
    architecture: str = "unknown"
    kernel_version: str = "unknown"
    cpu_count: int = 0
    memory_total: int = 0
    disk_usage: float = 0.0
    load_average: Tuple[float, float, float] = (0.0, 0.0, 0.0)
    uptime: float = 0.0
    
    # 服务状态
    ssh_active: bool = False
    cron_active: bool = False
    systemd_active: bool = False
    
    # 安全特性
    selinux_enabled: bool = False
    apparmor_enabled: bool = False
    firewall_active: bool = False
    
    # 监控和安全产品
    security_products: List[str] = None
    monitoring_services: List[str] = None
    
    # 网络信息
    network_interfaces: List[str] = None
    listening_ports: List[int] = None
    
    # 企业环境相关属性
    domain_joined: bool = False
    running_services: List[str] = None
    group_policy_applied: bool = False
    user_profile_path: str = ""
    user_accounts: List[str] = None
    installed_software: List[str] = None
    
    # 云环境相关属性
    cloud_metadata_accessible: bool = False
    instance_type: str = ""
    has_elastic_ip: bool = False
    
    # 容器环境相关属性
    container_runtime: str = ""
    mounted_filesystems: List[str] = None
    
    # 系统详细信息
    hostname: str = ""
    filesystem_types: List[str] = None
    environment_variables: List[str] = None
    cpu_architecture: str = ""
    disk_total: int = 0
    shell_type: str = ""
    
    # 安全配置
    selinux_mode: str = ""
    firewall_rules: List[str] = None
    audit_logging_enabled: bool = False
    ssh_key_auth_enabled: bool = False
    
    # 集群相关
    cluster_member: bool = False
    is_virtual_machine: bool = False
    
    def __post_init__(self):
        if self.security_products is None:
            self.security_products = []
        if self.monitoring_services is None:
            self.monitoring_services = []
        if self.network_interfaces is None:
            self.network_interfaces = []
        if self.listening_ports is None:
            self.listening_ports = []
        if self.running_services is None:
            self.running_services = []
        if self.user_accounts is None:
            self.user_accounts = []
        if self.installed_software is None:
            self.installed_software = []
        if self.mounted_filesystems is None:
            self.mounted_filesystems = []
        if self.filesystem_types is None:
            self.filesystem_types = []
        if self.environment_variables is None:
            self.environment_variables = []
        if self.firewall_rules is None:
            self.firewall_rules = []


@dataclass
class BackdoorRecommendation:
    """后门推荐信息"""
    backdoor_type: BackdoorType
    priority: int  # 1-10, 10为最高优先级
    success_probability: float  # 0.0-1.0
    stealth_level: float  # 0.0-1.0
    persistence_level: float  # 0.0-1.0
    risk_level: ThreatLevel
    reasons: List[str]
    parameters: Dict[str, Any]
    warnings: List[str] = None
    
    def __post_init__(self):
        if self.warnings is None:
            self.warnings = []


class EnvironmentCollector:
    """环境信息收集器"""
    
    def __init__(self):
        self.name = "环境信息收集器"
    
    def collect_system_info(self) -> SystemEnvironment:
        """收集系统环境信息"""
        env = SystemEnvironment()
        
        try:
            # 基本系统信息
            env.distro = detect_linux_distro()
            
            # 兼容性处理：Windows系统没有os.uname()
            try:
                # Linux系统架构检测
                env.architecture = os.uname().machine
                # Linux系统内核版本检测
                env.kernel_version = os.uname().release
            except AttributeError:
                # Windows系统处理
                import platform
                env.architecture = platform.machine()
                env.kernel_version = platform.release()
            
            # 硬件信息
            env.cpu_count = psutil.cpu_count()
            env.memory_total = psutil.virtual_memory().total
            
            # 磁盘使用率
            try:
                env.disk_usage = psutil.disk_usage('/').percent
            except:
                # Windows系统使用C盘
                try:
                    env.disk_usage = psutil.disk_usage('C:\\').percent
                except:
                    env.disk_usage = 0.0
            
            # 负载平均值（仅Linux）
            try:
                env.load_average = os.getloadavg()
            except AttributeError:
                env.load_average = (0.0, 0.0, 0.0)
            
            env.uptime = time.time() - psutil.boot_time()
            
            # 服务状态检测
            env.ssh_active = self._check_service_status(['ssh', 'sshd'])
            env.cron_active = self._check_service_status(['cron', 'crond'])
            env.systemd_active = self._check_service_status(['systemd'])
            
            # 安全特性检测
            env.selinux_enabled = self._check_selinux()
            env.apparmor_enabled = self._check_apparmor()
            env.firewall_active = self._check_firewall()
            
            # 安全产品检测
            env.security_products = self._detect_security_products()
            env.monitoring_services = self._detect_monitoring_services()
            
            # 网络信息
            env.network_interfaces = list(psutil.net_if_addrs().keys())
            env.listening_ports = self._get_listening_ports()
            
            # 新增属性收集
            env.domain_joined = self._check_domain_joined()
            env.running_services = self._get_running_services()
            env.group_policy_applied = self._check_group_policy()
            env.user_profile_path = self._get_user_profile_path()
            env.user_accounts = self._get_user_accounts()
            env.installed_software = self._get_installed_software()
            
            # 云环境检测
            env.cloud_metadata_accessible = self._check_cloud_metadata()
            env.instance_type = self._get_instance_type()
            env.has_elastic_ip = self._check_elastic_ip()
            
            # 容器环境检测
            env.container_runtime = self._detect_container_runtime()
            env.mounted_filesystems = self._get_mounted_filesystems()
            
            # 系统详细信息
            env.hostname = self._get_hostname()
            env.filesystem_types = self._get_filesystem_types()
            env.environment_variables = self._get_environment_variables()
            env.cpu_architecture = env.architecture  # 复用架构信息
            env.disk_total = self._get_disk_total()
            env.shell_type = self._get_shell_type()
            
            # 安全配置
            env.selinux_mode = self._get_selinux_mode()
            env.firewall_rules = self._get_firewall_rules()
            env.audit_logging_enabled = self._check_audit_logging()
            env.ssh_key_auth_enabled = self._check_ssh_key_auth()
            
            # 集群相关
            env.cluster_member = self._check_cluster_membership()
            env.is_virtual_machine = self._check_virtual_machine()
            
        except Exception as e:
            color_red("环境信息收集失败: {}".format(e))
        
        return env
    
    def _check_service_status(self, service_names: List[str]) -> bool:
        """检查服务状态"""
        for service in service_names:
            try:
                result = subprocess.run(
                    ['systemctl', 'is-active', service],
                    capture_output=True, text=True, timeout=5
                )
                if result.returncode == 0 and 'active' in result.stdout:
                    return True
            except:
                continue
        return False
    
    def _check_selinux(self) -> bool:
        """检查SELinux状态"""
        try:
            result = subprocess.run(
                ['getenforce'], capture_output=True, text=True, timeout=5
            )
            return result.returncode == 0 and 'Enforcing' in result.stdout
        except:
            return False
    
    def _check_apparmor(self) -> bool:
        """检查AppArmor状态"""
        try:
            result = subprocess.run(
                ['aa-status'], capture_output=True, text=True, timeout=5
            )
            return result.returncode == 0
        except:
            return False
    
    def _check_firewall(self) -> bool:
        """检查防火墙状态"""
        firewalls = ['ufw', 'firewalld', 'iptables']
        for fw in firewalls:
            try:
                if fw == 'ufw':
                    result = subprocess.run(['ufw', 'status'], capture_output=True, text=True, timeout=5)
                    if 'Status: active' in result.stdout:
                        return True
                elif fw == 'firewalld':
                    result = subprocess.run(['firewall-cmd', '--state'], capture_output=True, text=True, timeout=5)
                    if result.returncode == 0:
                        return True
                elif fw == 'iptables':
                    result = subprocess.run(['iptables', '-L'], capture_output=True, text=True, timeout=5)
                    if result.returncode == 0 and len(result.stdout.split('\n')) > 10:
                        return True
            except:
                continue
        return False
    
    def _detect_security_products(self) -> List[str]:
        """检测安全产品"""
        security_products = []
        
        # 常见安全产品进程名
        security_processes = [
            'clamd', 'freshclam',  # ClamAV
            'rkhunter', 'chkrootkit',  # Rootkit检测
            'aide', 'tripwire',  # 文件完整性检测
            'ossec', 'wazuh',  # HIDS
            'suricata', 'snort',  # IDS/IPS
            'fail2ban',  # 入侵防护
            'lynis',  # 安全审计
        ]
        
        try:
            for proc in psutil.process_iter(['name']):
                if proc.info['name'] in security_processes:
                    security_products.append(proc.info['name'])
        except:
            pass
        
        return list(set(security_products))
    
    def _detect_monitoring_services(self) -> List[str]:
        """检测监控服务"""
        monitoring_services = []
        
        # 常见监控服务
        monitoring_processes = [
            'rsyslog', 'syslog-ng',  # 日志服务
            'auditd',  # 审计服务
            'collectd', 'telegraf',  # 指标收集
            'filebeat', 'logstash',  # 日志收集
            'node_exporter', 'prometheus',  # 监控
            'zabbix_agentd', 'nagios',  # 监控代理
        ]
        
        try:
            for proc in psutil.process_iter(['name']):
                if proc.info['name'] in monitoring_processes:
                    monitoring_services.append(proc.info['name'])
        except:
            pass
        
        return list(set(monitoring_services))
    
    def _get_listening_ports(self) -> List[int]:
        """获取监听端口"""
        ports = []
        try:
            for conn in psutil.net_connections(kind='inet'):
                if conn.status == 'LISTEN' and conn.laddr:
                    ports.append(conn.laddr.port)
        except:
            pass
        return sorted(list(set(ports)))
    
    def _check_domain_joined(self) -> bool:
        """检查是否加入域"""
        try:
            # Windows域检查
            if os.name == 'nt':
                result = subprocess.run(['wmic', 'computersystem', 'get', 'domain'], 
                                      capture_output=True, text=True, timeout=5)
                if result.returncode == 0 and 'WORKGROUP' not in result.stdout.upper():
                    return True
            
            # Linux域检查（Samba/Winbind）
            domain_files = ['/etc/krb5.conf', '/etc/samba/smb.conf']
            for file_path in domain_files:
                if os.path.exists(file_path):
                    return True
        except:
            pass
        return False
    
    def _get_running_services(self) -> List[str]:
        """获取运行中的服务"""
        services = []
        try:
            for proc in psutil.process_iter(['name']):
                if proc.info['name']:
                    services.append(proc.info['name'])
        except:
            pass
        return sorted(list(set(services)))
    
    def _check_group_policy(self) -> bool:
        """检查组策略是否应用"""
        try:
            if os.name == 'nt':
                # Windows组策略检查
                result = subprocess.run(['gpresult', '/r'], 
                                      capture_output=True, text=True, timeout=10)
                return result.returncode == 0 and 'Computer Configuration' in result.stdout
        except:
            pass
        return False
    
    def _get_user_profile_path(self) -> str:
        """获取用户配置文件路径"""
        try:
            return os.path.expanduser('~')
        except:
            return ""
    
    def _get_user_accounts(self) -> List[str]:
        """获取用户账户列表"""
        users = []
        try:
            for user in psutil.users():
                if user.name not in users:
                    users.append(user.name)
        except:
            pass
        return sorted(users)
    
    def _get_installed_software(self) -> List[str]:
        """获取已安装软件列表（简化版）"""
        software = []
        try:
            # 检查常见软件目录
            common_paths = ['/usr/bin', '/usr/local/bin', 'C:\\Program Files', 'C:\\Program Files (x86)']
            for path in common_paths:
                if os.path.exists(path):
                    try:
                        items = os.listdir(path)[:20]  # 限制数量
                        software.extend(items)
                    except:
                        continue
        except:
            pass
        return sorted(list(set(software)))[:50]  # 限制返回数量
    
    def _check_cloud_metadata(self) -> bool:
        """检查云元数据可访问性"""
        try:
            import urllib.request
            # AWS元数据服务
            req = urllib.request.Request('http://169.254.169.254/latest/meta-data/', 
                                       headers={'User-Agent': 'Mozilla/5.0'})
            urllib.request.urlopen(req, timeout=2)
            return True
        except:
            pass
        return False
    
    def _get_instance_type(self) -> str:
        """获取实例类型"""
        try:
            import urllib.request
            req = urllib.request.Request('http://169.254.169.254/latest/meta-data/instance-type',
                                       headers={'User-Agent': 'Mozilla/5.0'})
            response = urllib.request.urlopen(req, timeout=2)
            return response.read().decode('utf-8')
        except:
            pass
        return ""
    
    def _check_elastic_ip(self) -> bool:
        """检查是否有弹性IP"""
        try:
            import urllib.request
            req = urllib.request.Request('http://169.254.169.254/latest/meta-data/public-ipv4',
                                       headers={'User-Agent': 'Mozilla/5.0'})
            response = urllib.request.urlopen(req, timeout=2)
            return bool(response.read().decode('utf-8'))
        except:
            pass
        return False
    
    def _detect_container_runtime(self) -> str:
        """检测容器运行时"""
        try:
            # 检查Docker
            if os.path.exists('/.dockerenv'):
                return "docker"
            
            # 检查其他容器标识
            if os.path.exists('/proc/1/cgroup'):
                with open('/proc/1/cgroup', 'r') as f:
                    content = f.read()
                    if 'docker' in content:
                        return "docker"
                    elif 'kubepods' in content:
                        return "kubernetes"
                    elif 'lxc' in content:
                        return "lxc"
        except:
            pass
        return ""
    
    def _get_mounted_filesystems(self) -> List[str]:
        """获取挂载的文件系统"""
        filesystems = []
        try:
            for partition in psutil.disk_partitions():
                filesystems.append(partition.mountpoint)
        except:
            pass
        return filesystems
    
    def _get_hostname(self) -> str:
        """获取主机名"""
        try:
            import socket
            return socket.gethostname()
        except:
            return ""
    
    def _get_filesystem_types(self) -> List[str]:
        """获取文件系统类型"""
        fs_types = []
        try:
            for partition in psutil.disk_partitions():
                if partition.fstype not in fs_types:
                    fs_types.append(partition.fstype)
        except:
            pass
        return fs_types
    
    def _get_environment_variables(self) -> List[str]:
        """获取环境变量（关键变量）"""
        key_vars = ['PATH', 'HOME', 'USER', 'SHELL', 'LANG', 'PWD']
        env_vars = []
        try:
            for var in key_vars:
                if var in os.environ:
                    env_vars.append(f"{var}={os.environ[var]}")
        except:
            pass
        return env_vars
    
    def _get_disk_total(self) -> int:
        """获取磁盘总容量"""
        try:
            if os.name == 'nt':
                return psutil.disk_usage('C:\\').total
            else:
                return psutil.disk_usage('/').total
        except:
            return 0
    
    def _get_shell_type(self) -> str:
        """获取Shell类型"""
        try:
            return os.environ.get('SHELL', 'unknown')
        except:
            return "unknown"
    
    def _get_selinux_mode(self) -> str:
        """获取SELinux模式"""
        try:
            result = subprocess.run(['getenforce'], capture_output=True, text=True, timeout=5)
            if result.returncode == 0:
                return result.stdout.strip()
        except:
            pass
        return ""
    
    def _get_firewall_rules(self) -> List[str]:
        """获取防火墙规则（简化版）"""
        rules = []
        try:
            # iptables规则
            result = subprocess.run(['iptables', '-L'], capture_output=True, text=True, timeout=5)
            if result.returncode == 0:
                lines = result.stdout.split('\n')[:10]  # 限制数量
                rules.extend([line.strip() for line in lines if line.strip()])
        except:
            pass
        return rules
    
    def _check_audit_logging(self) -> bool:
        """检查审计日志是否启用"""
        try:
            return self._check_service_status(['auditd'])
        except:
            pass
        return False
    
    def _check_ssh_key_auth(self) -> bool:
        """检查SSH密钥认证是否启用"""
        try:
            ssh_config_paths = ['/etc/ssh/sshd_config', '~/.ssh/config']
            for config_path in ssh_config_paths:
                expanded_path = os.path.expanduser(config_path)
                if os.path.exists(expanded_path):
                    with open(expanded_path, 'r') as f:
                        content = f.read()
                        if 'PubkeyAuthentication yes' in content:
                            return True
        except:
            pass
        return False
    
    def _check_cluster_membership(self) -> bool:
        """检查集群成员身份"""
        try:
            # 检查Kubernetes
            if os.path.exists('/var/lib/kubelet'):
                return True
            
            # 检查其他集群标识
            cluster_files = ['/etc/kubernetes', '/opt/kubernetes']
            for path in cluster_files:
                if os.path.exists(path):
                    return True
        except:
            pass
        return False
    
    def _check_virtual_machine(self) -> bool:
        """检查是否为虚拟机"""
        try:
            # 检查虚拟化标识
            vm_indicators = [
                '/sys/class/dmi/id/product_name',
                '/sys/class/dmi/id/sys_vendor'
            ]
            
            for indicator in vm_indicators:
                if os.path.exists(indicator):
                    with open(indicator, 'r') as f:
                        content = f.read().lower()
                        vm_keywords = ['vmware', 'virtualbox', 'qemu', 'kvm', 'xen', 'hyper-v']
                        if any(keyword in content for keyword in vm_keywords):
                            return True
        except:
            pass
        return False


class IntelligentDecisionEngine:
    """智能决策引擎"""
    
    def __init__(self):
        self.name = "智能决策引擎"
        self.collector = EnvironmentCollector()
        self.environment = None
        
        # 后门类型权重配置
        self.backdoor_weights = {
            BackdoorType.SSH_KEY: {
                'base_priority': 8,
                'stealth': 0.7,
                'persistence': 0.9,
                'complexity': 0.3
            },
            BackdoorType.CRONTAB: {
                'base_priority': 7,
                'stealth': 0.6,
                'persistence': 0.8,
                'complexity': 0.4
            },
            BackdoorType.SYSTEM_SERVICE: {
                'base_priority': 9,
                'stealth': 0.8,
                'persistence': 0.9,
                'complexity': 0.6
            },
            BackdoorType.BASH_ALIAS: {
                'base_priority': 5,
                'stealth': 0.8,
                'persistence': 0.5,
                'complexity': 0.3
            },
            BackdoorType.ENVIRONMENT: {
                'base_priority': 6,
                'stealth': 0.7,
                'persistence': 0.6,
                'complexity': 0.4
            },
            BackdoorType.SSH_CONFIG: {
                'base_priority': 8,
                'stealth': 0.6,
                'persistence': 0.8,
                'complexity': 0.5
            },
            BackdoorType.NETWORK: {
                'base_priority': 7,
                'stealth': 0.5,
                'persistence': 0.7,
                'complexity': 0.7
            },
            BackdoorType.STRACE: {
                'base_priority': 4,
                'stealth': 0.9,
                'persistence': 0.4,
                'complexity': 0.8
            },
            BackdoorType.USER_ACCOUNT: {
                'base_priority': 6,
                'stealth': 0.3,
                'persistence': 0.8,
                'complexity': 0.2

            },
            # 新增后门类型权重配置
            # BackdoorType.KERNEL_MODULE: {  # 已禁用，不采用内核级后门
            #     'base_priority': 9,
            #     'stealth': 0.95,
            #     'persistence': 0.9,
            #     'complexity': 0.9
            # },
            BackdoorType.LIBRARY_HIJACK: {
                'base_priority': 8,
                'stealth': 0.85,
                'persistence': 0.8,
                'complexity': 0.7
            },
            BackdoorType.CONTAINER_ESCAPE: {
                'base_priority': 8,
                'stealth': 0.7,
                'persistence': 0.6,
                'complexity': 0.8
            },
            BackdoorType.DOCKER_SOCKET: {
                'base_priority': 7,
                'stealth': 0.6,
                'persistence': 0.7,
                'complexity': 0.6
            },
            BackdoorType.SYSTEMD_TIMER: {
                'base_priority': 7,
                'stealth': 0.7,
                'persistence': 0.8,
                'complexity': 0.5
            },
            # BackdoorType.PAM_MODULE: {  # 已禁用，不采用PAM模块后门
            #     'base_priority': 8,
            #     'stealth': 0.8,
            #     'persistence': 0.9,
            #     'complexity': 0.8
            # },
            BackdoorType.IPTABLES_RULE: {
                'base_priority': 6,
                'stealth': 0.7,
                'persistence': 0.6,
                'complexity': 0.7
            },
            BackdoorType.DNS_HIJACK: {
                'base_priority': 5,
                'stealth': 0.6,
                'persistence': 0.5,
                'complexity': 0.4
            },
            BackdoorType.PROCESS_INJECT: {
                'base_priority': 7,
                'stealth': 0.8,
                'persistence': 0.4,
                'complexity': 0.8
            },
            BackdoorType.MEMORY_RESIDENT: {
                'base_priority': 8,
                'stealth': 0.9,
                'persistence': 0.3,
                'complexity': 0.9
            }
        }
    
    def analyze_environment(self, external_env: SystemEnvironment = None) -> SystemEnvironment:
        """分析系统环境，可以使用外部提供的环境信息"""
        if external_env:
            color_blue("🔍 使用外部提供的环境信息...")
            self.environment = external_env
        else:
            color_blue("🔍 正在收集环境信息...")
            self.environment = self.collector.collect_system_info()
            color_green("✓ 环境信息收集完成")
        return self.environment
    
    def recommend_backdoors(self, external_env: SystemEnvironment = None, max_recommendations: int = 3) -> List[BackdoorRecommendation]:
        """推荐后门类型"""
        if external_env:
            self.environment = external_env
        elif not self.environment:
            self.analyze_environment()
        
        color_blue("🧠 正在分析最佳后门策略...")
        
        recommendations = []
        
        for backdoor_type in BackdoorType:
            recommendation = self._evaluate_backdoor(backdoor_type)
            if recommendation:
                recommendations.append(recommendation)
        
        # 按优先级排序
        recommendations.sort(key=lambda x: x.priority, reverse=True)
        
        color_green("✓ 生成了 {} 个后门推荐".format(len(recommendations)))
        return recommendations[:max_recommendations]
    
    def _evaluate_backdoor(self, backdoor_type: BackdoorType) -> Optional[BackdoorRecommendation]:
        """评估单个后门类型"""
        weights = self.backdoor_weights[backdoor_type]
        reasons = []
        warnings = []
        parameters = {}
        
        # 基础优先级
        priority = weights['base_priority']
        success_prob = 0.7  # 基础成功率
        
        # 环境特征评估
        env_score = self._calculate_environment_score(backdoor_type)
        priority += env_score
        success_prob += env_score * 0.1
        
        # 根据环境调整评分
        if backdoor_type == BackdoorType.SSH_KEY:
            if safe_getattr(self.environment, 'ssh_active', False):
                priority += 2
                success_prob += 0.2
                reasons.append("SSH服务运行中，适合密钥后门")
            else:
                priority -= 3
                success_prob -= 0.3
                warnings.append("SSH服务未运行")
            
            # 参数配置
            parameters = {
                'key_type': 'rsa',
                'key_size': 2048,
                'key_comment': "user@{}".format(safe_getattr(self.environment, 'distro', 'unknown'))
            }
        
        elif backdoor_type == BackdoorType.CRONTAB:
            if safe_getattr(self.environment, 'cron_active', False):
                priority += 2
                success_prob += 0.2
                reasons.append("Cron服务运行中，适合定时任务后门")
            else:
                priority -= 3
                success_prob -= 0.3
                warnings.append("Cron服务未运行")
            
            # 根据系统负载调整执行频率
            load_average = safe_getattr(self.environment, 'load_average', (0.0, 0.0, 0.0))
            load_avg = load_average[0] if load_average else 0.0
            if load_avg > 2.0:
                interval = "*/15 * * * *"  # 高负载时降低频率
                warnings.append("系统负载较高，建议降低执行频率")
            elif load_avg > 1.0:
                interval = "*/10 * * * *"
            else:
                interval = "*/5 * * * *"
            
            parameters = {
                'interval': interval,
                'command_type': 'reverse_shell',
                'stealth_mode': True
            }
        
        elif backdoor_type == BackdoorType.SYSTEM_SERVICE:
            if safe_getattr(self.environment, 'systemd_active', False):
                priority += 2
                success_prob += 0.2
                reasons.append("Systemd运行中，适合服务后门")
            else:
                priority -= 2
                success_prob -= 0.2
                warnings.append("Systemd未运行，可能需要使用init.d")
            
            parameters = {
                'service_name': "system-{}".format(safe_getattr(self.environment, 'distro', 'unknown')),
                'service_type': 'forking',
                'restart_policy': 'always'
            }
        
        elif backdoor_type == BackdoorType.BASH_ALIAS:
            if 'bash' in os.environ.get('SHELL', ''):
                priority += 1
                success_prob += 0.1
                reasons.append("当前使用Bash shell")
            
            parameters = {
                'target_command': 'ls',
                'alias_file': '~/.bashrc',
                'stealth_mode': True
            }
        
        elif backdoor_type == BackdoorType.STRACE:
            # 在高负载系统上降低strace后门优先级
            if self.environment.load_average[0] > 1.5:
                priority -= 2
                warnings.append("系统负载较高，strace可能影响性能")
            
            # 根据内存调整采样频率
            memory_gb = self.environment.memory_total / (1024**3)
            if memory_gb < 2:
                sample_rate = 0.1
                warnings.append("内存较少，建议降低采样频率")
            else:
                sample_rate = 0.5
            
            parameters = {
                'target_process': 'sshd',
                'sample_rate': sample_rate,
                'log_file': '/tmp/.strace.log'
            }
        
        # elif backdoor_type == BackdoorType.KERNEL_MODULE:
        #     # 内核模块后门需要root权限和内核开发环境 - 已禁用，不采用内核级后门
        #     try:
        #         is_root = os.geteuid() == 0
        #     except AttributeError:
        #         # Windows系统没有geteuid，检查是否为管理员
        #         import ctypes
        #         is_root = ctypes.windll.shell32.IsUserAnAdmin() != 0
        #     
        #     if is_root:
        #         priority += 2
        #         success_prob += 0.2
        #         reasons.append("具有管理员权限，适合内核模块后门")
        #     else:
        #         priority -= 3
        #         success_prob -= 0.4
        #         warnings.append("需要管理员权限")
        #     
        #     parameters = {
        #         'module_name': 'netfilter_hook',
        #         'hide_process': True,
        #         'hide_files': True,
        #         'rootkit_mode': True
        #     }
        
        elif backdoor_type == BackdoorType.LIBRARY_HIJACK:
            # 库劫持后门适合有写权限的环境
            priority += 1
            success_prob += 0.15
            reasons.append("库劫持隐蔽性较高")
            
            parameters = {
                'target_library': 'libc.so.6',
                'hook_functions': ['execve', 'open', 'stat'],
                'stealth_mode': True
            }
        
        elif backdoor_type == BackdoorType.CONTAINER_ESCAPE:
            # 容器逃逸需要容器环境
            if os.path.exists('/.dockerenv') or os.path.exists('/proc/1/cgroup'):
                priority += 3
                success_prob += 0.3
                reasons.append("检测到容器环境")
            else:
                priority -= 2
                success_prob -= 0.3
                warnings.append("非容器环境")
            
            parameters = {
                'escape_method': 'privileged_container',
                'target_host': True,
                'persistence_method': 'crontab'
            }
        
        elif backdoor_type == BackdoorType.DOCKER_SOCKET:
            # Docker socket后门需要Docker环境
            if os.path.exists('/var/run/docker.sock'):
                priority += 2
                success_prob += 0.25
                reasons.append("检测到Docker socket")
            else:
                priority -= 3
                success_prob -= 0.4
                warnings.append("Docker未安装或socket不可访问")
            
            parameters = {
                'socket_path': '/var/run/docker.sock',
                'container_image': 'alpine:latest',
                'mount_host_root': True
            }
        
        elif backdoor_type == BackdoorType.SYSTEMD_TIMER:
            # Systemd定时器需要systemd环境
            if self.environment.systemd_active:
                priority += 2
                success_prob += 0.2
                reasons.append("Systemd运行中，适合定时器后门")
            else:
                priority -= 3
                success_prob -= 0.3
                warnings.append("Systemd未运行")
            
            parameters = {
                'timer_name': 'system-maintenance',
                'schedule': 'daily',
                'persistent': True
            }
        
        # elif backdoor_type == BackdoorType.PAM_MODULE:
        #     # PAM模块后门需要root权限 - 已禁用，不采用PAM模块后门
        #     try:
        #         is_root = os.geteuid() == 0
        #     except AttributeError:
        #         # Windows系统没有geteuid，检查是否为管理员
        #         import ctypes
        #         is_root = ctypes.windll.shell32.IsUserAnAdmin() != 0
        #     
        #     if is_root:
        #         priority += 2
        #         success_prob += 0.2
        #         reasons.append("具有管理员权限，适合PAM模块后门")
        #     else:
        #         priority -= 3
        #         success_prob -= 0.4
        #         warnings.append("需要管理员权限")
        #     
        #     parameters = {
        #         'module_name': 'pam_backdoor.so',
        #         'target_service': 'sshd',
        #         'trigger_password': 'backdoor123'
        #     }
        
        elif backdoor_type == BackdoorType.IPTABLES_RULE:
            # iptables规则后门需要root权限和iptables
            try:
                is_root = os.geteuid() == 0
            except AttributeError:
                # 非Unix系统，无法检查权限
                is_root = False
            
            if is_root:
                priority += 1
                success_prob += 0.15
                reasons.append("具有管理员权限")
            else:
                priority -= 2
                success_prob -= 0.3
                warnings.append("需要管理员权限")
            
            parameters = {
                'target_port': 31337,
                'trigger_packet': 'magic_string',
                'action': 'reverse_shell'
            }
        
        elif backdoor_type == BackdoorType.DNS_HIJACK:
            # DNS劫持后门
            priority += 1
            success_prob += 0.1
            reasons.append("DNS劫持隐蔽性较好")
            
            parameters = {
                'target_domain': 'update.example.com',
                'redirect_ip': '127.0.0.1',
                'method': 'hosts_file'
            }
        
        elif backdoor_type == BackdoorType.PROCESS_INJECT:
            # 进程注入后门
            priority += 1
            success_prob += 0.12
            reasons.append("进程注入难以检测")
            
            parameters = {
                'target_process': 'systemd',
                'injection_method': 'ptrace',
                'payload_type': 'shellcode'
            }
        
        elif backdoor_type == BackdoorType.MEMORY_RESIDENT:
            # 内存驻留后门
            priority += 2
            success_prob += 0.18
            reasons.append("内存驻留无文件痕迹")
            
            parameters = {
                'persistence_method': 'process_hollowing',
                'target_process': 'init',
                'stealth_techniques': ['anti_debug', 'obfuscation']
            }
        
        # 安全产品检测调整
        if self.environment.security_products:
            if backdoor_type in [BackdoorType.USER_ACCOUNT, BackdoorType.NETWORK]:
                priority -= 2
                warnings.append("检测到安全产品: {}".format(', '.join(self.environment.security_products)))
        
        # SELinux/AppArmor调整
        if self.environment.selinux_enabled or self.environment.apparmor_enabled:
            if backdoor_type == BackdoorType.SYSTEM_SERVICE:
                priority -= 1
                warnings.append("SELinux/AppArmor可能阻止服务后门")
        
        # 防火墙调整
        if self.environment.firewall_active:
            if backdoor_type == BackdoorType.NETWORK:
                priority -= 2
                warnings.append("防火墙可能阻止网络后门")
        
        # 计算风险等级
        risk_level = self._calculate_risk_level(backdoor_type, priority, self.environment)
        
        # 确保数值在合理范围内
        priority = max(1, min(10, priority))
        success_prob = max(0.1, min(1.0, success_prob))
        
        return BackdoorRecommendation(
            backdoor_type=backdoor_type,
            priority=priority,
            success_probability=success_prob,
            stealth_level=weights['stealth'],
            persistence_level=weights['persistence'],
            risk_level=risk_level,
            reasons=reasons,
            parameters=parameters,
            warnings=warnings
        )
    
    def _calculate_environment_score(self, backdoor_type: BackdoorType) -> float:
        """根据环境特征计算后门类型的适应性评分"""
        score = 0.0
        
        # 基于发行版的评分调整
        distro = safe_getattr(self.environment, 'distro', 'unknown')
        distro_lower = distro.lower() if distro else 'unknown'
        
        if backdoor_type == BackdoorType.BASH_ALIAS:
            # Bash别名在所有Linux发行版都很有效
            score += 2.0
            if distro_lower in ['ubuntu', 'debian']:
                score += 1.0  # Ubuntu/Debian默认使用bash
            elif distro_lower in ['centos', 'rhel']:
                score += 0.5  # CentOS可能使用其他shell
        
        elif backdoor_type == BackdoorType.SSH_KEY:
            # SSH密钥在有SSH服务的环境中优先级高
            if safe_getattr(self.environment, 'ssh_active', False):
                score += 2.0
            if distro_lower in ['ubuntu', 'debian', 'alpine']:
                score += 1.0  # 这些发行版通常启用SSH
        
        elif backdoor_type == BackdoorType.CRONTAB:
            # Cron任务在服务器环境中很有效
            if safe_getattr(self.environment, 'cron_active', False):
                score += 2.0
            if distro_lower in ['ubuntu', 'centos', 'debian']:
                score += 1.0  # 服务器发行版
            elif distro_lower == 'alpine':
                score -= 1.0  # 容器环境可能没有cron
        
        elif backdoor_type == BackdoorType.SYSTEM_SERVICE:
            # 系统服务在有systemd的环境中优先级高
            if safe_getattr(self.environment, 'systemd_active', False):
                score += 2.0
            if distro_lower in ['centos', 'rhel']:
                score += 1.5  # CentOS更适合服务后门
            elif distro_lower == 'alpine':
                score -= 2.0  # Alpine通常不用systemd
        
        elif backdoor_type == BackdoorType.ENVIRONMENT:
            # 环境变量后门在容器和受限环境中很有效
            if distro_lower == 'alpine':
                score += 2.0  # 容器环境
            security_products = safe_getattr(self.environment, 'security_products', [])
            if security_products:
                score += 1.5  # 有安全产品时，环境变量更隐蔽
            if distro_lower in ['centos', 'rhel']:
                score += 1.0  # 企业环境
        
        # 新增后门类型的评分逻辑
        # elif backdoor_type == BackdoorType.KERNEL_MODULE:
        #     # 内核模块后门需要root权限和内核开发环境 - 已禁用，不采用内核级后门
        #     if distro_lower in ['centos', 'rhel']:
        #         score += 2.0  # 企业环境通常有内核开发工具
        #     elif distro_lower == 'alpine':
        #         score -= 2.0  # 容器环境通常没有内核模块支持
        #     if self.environment.security_products:
        #         score -= 1.0  # 安全产品可能检测内核模块
        
        elif backdoor_type == BackdoorType.LIBRARY_HIJACK:
            # 库劫持在有动态链接库的环境中有效
            if distro_lower in ['ubuntu', 'debian']:
                score += 1.5  # 这些发行版有丰富的库环境
            if self.environment.security_products:
                score -= 1.0  # 可能被检测
        
        elif backdoor_type == BackdoorType.CONTAINER_ESCAPE:
            # 容器逃逸专门针对容器环境
            if distro_lower == 'alpine':
                score += 3.0  # 容器环境的主要目标
            elif 'docker' in str(self.environment.network_interfaces):
                score += 2.0  # 检测到Docker网络接口
            else:
                score -= 3.0  # 非容器环境不适用
        
        elif backdoor_type == BackdoorType.DOCKER_SOCKET:
            # Docker套接字后门需要Docker环境
            if 'docker' in str(self.environment.network_interfaces):
                score += 3.0  # Docker环境
            else:
                score -= 3.0  # 非Docker环境不适用
        
        elif backdoor_type == BackdoorType.SYSTEMD_TIMER:
            # Systemd定时器需要systemd支持
            if self.environment.systemd_active:
                score += 2.5  # 有systemd支持
                if distro_lower in ['centos', 'rhel', 'ubuntu']:
                    score += 1.0  # 这些发行版广泛使用systemd
            else:
                score -= 3.0  # 没有systemd支持
        
        # elif backdoor_type == BackdoorType.PAM_MODULE:
        #     # PAM模块后门在企业环境中有效 - 已禁用，不采用PAM模块后门
        #     if distro_lower in ['centos', 'rhel']:
        #         score += 2.0  # 企业环境通常使用PAM
        #     if self.environment.security_products:
        #         score -= 0.5  # 可能被检测
        
        elif backdoor_type == BackdoorType.IPTABLES_RULE:
            # iptables规则后门需要防火墙环境
            if self.environment.firewall_active:
                score += 2.0  # 有防火墙环境
            if distro_lower in ['centos', 'rhel']:
                score += 1.0  # 企业环境通常使用iptables
        
        elif backdoor_type == BackdoorType.DNS_HIJACK:
            # DNS劫持在网络环境中有效
            if len(self.environment.network_interfaces) > 2:
                score += 1.5  # 多网络接口环境
            if self.environment.firewall_active:
                score -= 1.0  # 防火墙可能阻止
        
        elif backdoor_type == BackdoorType.PROCESS_INJECT:
            # 进程注入需要目标进程
            if self.environment.cpu_count > 4:
                score += 1.0  # 多核环境通常有更多进程
            if self.environment.security_products:
                score -= 2.0  # 容易被EDR检测
        
        elif backdoor_type == BackdoorType.MEMORY_RESIDENT:
            # 内存驻留后门在高内存环境中有效
            if self.environment.memory_total > 8 * 1024**3:  # 8GB以上
                score += 1.5  # 高内存环境
            if self.environment.security_products:
                score -= 1.5  # 可能被内存扫描检测
        
        # 安全特征调整
        if self.environment.selinux_enabled or self.environment.apparmor_enabled:
            if backdoor_type in [BackdoorType.BASH_ALIAS, BackdoorType.ENVIRONMENT]:
                score += 1.0  # 这些后门在强制访问控制下更隐蔽
            elif backdoor_type == BackdoorType.SYSTEM_SERVICE:
                score -= 1.0  # 服务后门可能被阻止
        
        # 防火墙调整
        if self.environment.firewall_active:
            if backdoor_type == BackdoorType.NETWORK:
                score -= 2.0  # 网络后门受防火墙影响
            elif backdoor_type in [BackdoorType.BASH_ALIAS, BackdoorType.ENVIRONMENT]:
                score += 0.5  # 本地后门不受防火墙影响
        
        # 安全产品调整
        if self.environment.security_products:
            if backdoor_type in [BackdoorType.BASH_ALIAS, BackdoorType.ENVIRONMENT]:
                score += 1.0  # 这些后门对EDR/AV更隐蔽
            elif backdoor_type in [BackdoorType.SYSTEM_SERVICE, BackdoorType.NETWORK]:
                score -= 1.0  # 这些后门容易被检测
        
        return score
    
    def _calculate_risk_level(self, backdoor_type: BackdoorType, priority: int, env: SystemEnvironment) -> ThreatLevel:
        """计算风险等级"""
        risk_score = 0
        
        # 基础风险
        if backdoor_type in [BackdoorType.USER_ACCOUNT, BackdoorType.NETWORK]:
            risk_score += 2
        elif backdoor_type in [BackdoorType.SYSTEM_SERVICE, BackdoorType.SSH_CONFIG]:
            risk_score += 1
        
        # 环境风险
        if env.security_products:
            risk_score += len(env.security_products)
        
        if env.monitoring_services:
            risk_score += len(env.monitoring_services) * 0.5
        
        if env.selinux_enabled or env.apparmor_enabled:
            risk_score += 1
        
        # 转换为等级
        if risk_score >= 4:
            return ThreatLevel.CRITICAL
        elif risk_score >= 3:
            return ThreatLevel.HIGH
        elif risk_score >= 2:
            return ThreatLevel.MEDIUM
        else:
            return ThreatLevel.LOW
    
    def get_environment_summary(self) -> Dict[str, Any]:
        """获取环境摘要"""
        if not self.environment:
            return {}
        
        return {
            'system': {
                'distro': self.environment.distro,
                'architecture': self.environment.architecture,
                'kernel': self.environment.kernel_version
            },
            'resources': {
                'cpu_count': self.environment.cpu_count,
                'memory_gb': round(self.environment.memory_total / (1024**3), 2),
                'disk_usage_percent': self.environment.disk_usage,
                'load_average': self.environment.load_average
            },
            'services': {
                'ssh': self.environment.ssh_active,
                'cron': self.environment.cron_active,
                'systemd': self.environment.systemd_active
            },
            'security': {
                'selinux': self.environment.selinux_enabled,
                'apparmor': self.environment.apparmor_enabled,
                'firewall': self.environment.firewall_active,
                'security_products': self.environment.security_products,
                'monitoring_services': self.environment.monitoring_services
            },
            'network': {
                'interfaces': len(self.environment.network_interfaces),
                'listening_ports': len(self.environment.listening_ports)
            }
        }
    
    def export_analysis(self, filename: str = None) -> str:
        """导出分析结果"""
        if not filename:
            filename = "environment_analysis_{}.json".format(int(time.time()))
        
        data = {
            'timestamp': time.time(),
            'environment': asdict(self.environment) if self.environment else {},
            'recommendations': [asdict(rec) for rec in self.recommend_backdoors()],
            'summary': self.get_environment_summary()
        }
        
        try:
            with open(filename, 'w', encoding='utf-8') as f:
                json.dump(data, f, indent=2, ensure_ascii=False, default=str)
            color_green("✓ 分析结果已导出到: {}".format(filename))
            return filename
        except Exception as e:
            color_red("导出失败: {}".format(e))
            return ""


def main():
    """测试智能决策引擎"""
    print("🤖 智能决策引擎测试")
    print("=" * 50)
    
    engine = IntelligentDecisionEngine()
    
    # 分析环境
    env = engine.analyze_environment()
    print(f"\n📊 环境摘要:")
    summary = engine.get_environment_summary()
    for category, data in summary.items():
        print("  {}: {}".format(category, data))
    
    # 获取推荐
    recommendations = engine.recommend_backdoors()
    print("\n🎯 后门推荐 (共{}个):".format(len(recommendations)))
    
    for i, rec in enumerate(recommendations, 1):
        print("\n[{}] {}".format(i, rec.backdoor_type.value))
        print("    优先级: {}/10".format(rec.priority))
        print("    成功率: {:.1%}".format(rec.success_probability))
        print("    隐蔽性: {:.1%}".format(rec.stealth_level))
        print("    持久性: {:.1%}".format(rec.persistence_level))
        print("    风险等级: {}".format(rec.risk_level.value))
        
        if rec.reasons:
            print("    推荐理由: {}".format(', '.join(rec.reasons)))
        
        if rec.warnings:
            print("    ⚠️  警告: {}".format(', '.join(rec.warnings)))
        
        if rec.parameters:
            print("    建议参数: {}".format(rec.parameters))
    
    # 导出结果
    engine.export_analysis()


if __name__ == "__main__":
    main()